package dto;

// Generated May 6, 2011 4:19:20 PM by Hibernate Tools 3.3.0.GA

import SessionFactory.SessionFactoryUtil;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import static org.hibernate.criterion.Example.create;

/**
 * Home object for domain model class JfMembers.
 * @see dto.JfMembers
 * @author Hibernate Tools
 */
public class JfMembersHome {
Vector<JfMembers> members = new Vector<JfMembers>();
	Vector<JfMembers> moderator = new Vector<JfMembers>();
	private static final Log log = LogFactory.getLog(JfMembersHome.class);

	private final SessionFactory sessionFactory = SessionFactoryUtil.getInstance();

	public void persist(JfMembers transientInstance) {
		log.debug("persisting JfMembers instance");
		try {
			sessionFactory.getCurrentSession().persist(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public void attachDirty(JfMembers instance) {
		log.debug("attaching dirty JfMembers instance");
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(JfMembers instance) {
		log.debug("attaching clean JfMembers instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void delete(JfMembers persistentInstance) {
		log.debug("deleting JfMembers instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public JfMembers merge(JfMembers detachedInstance) {
		log.debug("merging JfMembers instance");
		try {
			JfMembers result = (JfMembers) sessionFactory.getCurrentSession()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public JfMembers findById(Integer id) {
		log.debug("getting JfMembers instance with id: " + id);
		try {
			JfMembers instance = (JfMembers) sessionFactory.getCurrentSession()
					.get("dto.JfMembers", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<JfMembers> findByExample(JfMembers instance) {
		log.debug("finding JfMembers instance by example");
		try {
			List<JfMembers> results = (List<JfMembers>) sessionFactory
					.getCurrentSession().createCriteria("dto.JfMembers").add(
							create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

        public JfMembers findByName(JfMembers member) {
            JfMembers memb     = new JfMembers();
            String    query    = "from JfMembers members where members.username like :name";
            Query     hqlQuery = sessionFactory.getCurrentSession().createQuery(query).setString("name", member.getUsername());
            List      myResult = hqlQuery.list();
            Iterator  it       = myResult.iterator();

            if (it.hasNext()) {
                memb = (JfMembers) it.next();
//                System.out.println(memb.getUsername());
//                System.out.println("pw=" + memb.getPassword());
//                System.out.println("id=" + memb.getMemberId());
            }

            return memb;
        }

        public int updategender(String gender, String username) {
//        System.out.println("Iam is" + gender + username);

        

        String hql   = "update JfMembers members set gender = :gender where username = :username";
        Query  query = sessionFactory.getCurrentSession().createQuery(hql);

        query.setString("gender", gender);
        query.setString("username", username);

        int rowCount = query.executeUpdate();

        
//        System.out.println("Rows affected: " + rowCount);

        return rowCount;
    }
     //==============================================================
        public int update(JfMembers mem)
        {
            String hql   = "update JfMembers members set FName = :FName,LName = :LName,country = :country,EMail = :EMail,avatar = :avatar,gender=:gender where username = :username"; 
            Query  query = sessionFactory.getCurrentSession().createQuery(hql);
            query.setString("FName", mem.getFName());
            query.setString("LName", mem.getLName());
            query.setString("country", mem.getCountry());
            query.setString("EMail", mem.getEMail());
            query.setString("avatar",mem.getAvatar());
            query.setString("username", mem.getUsername());
            query.setString("gender", mem.getGender());
            int rowCount = query.executeUpdate();
            System.out.println("Rows affected: " + rowCount);
           return rowCount; 
        }
    // ==============================================================
    public int updatepw(String password, String username) {

        
        String hql   = "update JfMembers members set password = :password where username = :username";
        Query  query = sessionFactory.getCurrentSession().createQuery(hql);

        query.setString("password", password);
        query.setString("username", username);

        int rowCount = query.executeUpdate();

        
//        System.out.println("Rows affected: " + rowCount);

        return rowCount;
    }

  
    public Vector<JfMembers> getAllUsers()
    {
        System.out.print("inside getallusers in member home");

        Vector<JfMembers> users = new Vector<JfMembers>();
        JfMembers user ;
        Criteria crit  = sessionFactory.getCurrentSession().createCriteria(JfMembers.class).add(Restrictions.eq("userprev", new Integer(0)));
        Iterator it = crit.list().iterator();
        while(it.hasNext())
        {
            user  = new JfMembers();
            user  = (JfMembers)it.next();
            users.add(user);
        }

        return users;
    }
	
	
	
	 ///////////////////////////////////////////////Admin//////////////////////////////////////////////////////////
    public Vector<JfMembers> getAllUsers1() {
		JfMembers mem = new JfMembers();
                sessionFactory.getCurrentSession().beginTransaction();
	    Query q = sessionFactory.getCurrentSession().createQuery("from JfMembers mem where mem.userprev = 0");
		Iterator  it = q.list().iterator();
	    while (it.hasNext()) {
			mem =(JfMembers)it.next();
		    members.add(mem);
		}
	    System.out.println(members);
            sessionFactory.getCurrentSession().close();
		return members;
	}

	public Vector<JfMembers> getModerators() {
		System.out.println("enter home");
	    JfMembers mem = new JfMembers();
	    Query q=null;
	    try{
//	    	sessionFactory.getCurrentSession().beginTransaction();
	    	SessionFactoryUtil.startNew();
		 q=sessionFactory.getCurrentSession().createQuery("from JfMembers mem where mem.userprev >:id");
                 q.setInteger("id",new Integer(1));
                 System.out.println("Query");
		System.out.println("moderator");
		Iterator  it = q.list().iterator();
                System.out.println(it);
	        while (it.hasNext()) {
			mem =(JfMembers)it.next();
		    moderator.add(mem);
		    System.out.println("moderator add to vector");
                     }
	          }catch (Exception e) {
			e.printStackTrace();
		   }

sessionFactory.getCurrentSession().close();
		return moderator;
	}

    public boolean demoteModerator(Integer id) {
    	boolean result=true;
    	try{
     //   sessionFactory.getCurrentSession().beginTransaction();
    	System.out.println("in mem hoome" +id);
    	Query q = sessionFactory.getCurrentSession().createQuery("update JfMembers mem set mem.userprev =:value where mem.memberId =:id ");
		q.setInteger("id",id);
		q.setInteger("value",new Integer(0));
		q.executeUpdate();
	//	sessionFactory.getCurrentSession().getTransaction().commit();
		System.out.println("in mem hoome after update" +id);
	   	
		//session.getTransaction().commit();

    	}catch (Exception e) {
    		e.printStackTrace();
			result=false;
		}
		return result;

	}

    public boolean promoteUser(Integer id,Integer type) {
    	boolean result=true;
        sessionFactory.getCurrentSession().beginTransaction();
    	Query q = sessionFactory.getCurrentSession().createQuery("update JfMembers set userprev =:type where memberId=:id");
		q.setInteger("id",id);
		q.setInteger("type", type);
		q.executeUpdate();              
                sessionFactory.getCurrentSession().getTransaction().commit();
		//JfMembers user = new JfMembers();

//		user = this.findById(id);
//		ModPrevHome mphome = new ModPrevHome();
////		for (int i = 0; i <Sections.size(); i++) {
//			ModPrev mp = new ModPrev();
//			mp.setJfMembers(user);
//                        Integer mpdid = new Integer(1);
//
//                        mp.setModPrevId(mpdid);
////			mp.setSections(Sections.get(i));
//		   	mphome.persist(mp);
//		}
//
//		sessionFactory.getCurrentSession().getTransaction().commit();
//    	}catch (Exception e) {
//			result=false;
//		}
		return result;

	}

    public boolean editModerator(JfMembers user, Integer type,Vector<Sections> Sections) {
boolean result=true;

    	try{
    		sessionFactory.getCurrentSession().beginTransaction();
    	Query q = sessionFactory.getCurrentSession().createQuery("update JfMembers set userprev =:type where memberId=:id");
		q.setInteger("id",user.getMemberId());
		q.setInteger("type", type);
		ModPrevHome mphome = new ModPrevHome();
		for (int i = 0; i <Sections.size(); i++) {
			ModPrev mp = new ModPrev();
			mp.setJfMembers(user);
			mp.setSections(Sections.get(i));
		   	mphome.persist(mp);
		}

		sessionFactory.getCurrentSession().getTransaction().commit();
    	}catch (Exception e) {
			result=false;
		}
		return result;

	}
//____________________________-check prev of access-_______________________
    public boolean checkprevelage(JfMembers member) {
        boolean result = false;
        Integer memID = member.getMemberId();
        member = findById(memID);
        int lowPrev= 0;
        Criteria create = sessionFactory.getCurrentSession().createCriteria(JfMembers.class).add(Restrictions.gt("userprev",lowPrev));
        Iterator it = create.list().iterator();
        if (it.hasNext()) {
            result = true;
        } else {
            result = false;
        }

        return result;
    }


}
